/**
 * Created by Administrator on 2017/2/20.
 */

var DBFactory = require('../db/mysql_db');
var async = require('async');
var adminManagementDao = module.exports;


adminManagementDao.resetAdmPwd = function(data, cb) {
    if(!data) {
        cb(new Error(500));
        return;
    }
    DBFactory.poolQuery('update admin set password = ? where uid = ?', [data.password,data.uid],
        function(){
           cb('no connection');
        },
        function(err, result){
            if(err) {
                cb(err);
                console.log(err);
                return;
            }
            cb(null, result);
        }
    );
}

adminManagementDao.changePwd = function(data, cb) {
    if(!data) {
        cb(new Error(500));
        return;
    }
    DBFactory.poolQuery('update admin set password = ? where uid = ?', [data.password,data.uid],
        function(){
            cb('no collection');
        },
        function(err, result){
            if(err) {
                cb(err);
                console.log(err);
                return;
            }
            cb(null, result);
        }
    );
}


adminManagementDao.addAdmin = function(data, cb) {
    if(!data) {
        cb(new Error(500));
        return;
    }
    DBFactory.getConnection(function(error, connection) {
        if(error) {
            cb(error);
            return;
        }
        
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function(err) {
                    callback(err);
                });
            },

            function (callback) {
                connection.query("select account from admin where account = ? limit 1",[data.account],function (err,result) {
                    var adminOld = (result && result.length > 0) ? result[0] : undefined;
                    callback(err, adminOld);
                });
            },

            //如果是添加产品管理员，判断该产品是否存在管理员
            function (userOld,callback) {
                if(userOld) {//已经有该管理员
                    callback('该管理员已存在!');
                    return;
                }

                //如果是添加产品管理员，多判断一下该产品是否有管理员，有添加失败，没有则加上
                if(data.role.indexOf('adm') >= 0){

                    connection.query("select adm_account from apps where sid = ?",[data.app_sid],function (err,result) {
                        if(err){
                            console.log('添加管理员时，查找apps表失败:' + err);
                            callback(err);
                            return;
                        }
                        var appInfo = (result && result.length > 0) ? result[0] : undefined;
                        console.log(appInfo);
                        if(appInfo.adm_account){
                            callback('该产品已有产品管理员');
                            return;
                        }

                        callback(null,'成功');

                    });


                }else {//添加功能管理员不用，直接添加
                    callback(null,'跳过');
                }


            },

            //增加管理员  如果是添加产品管理员，添加该管理员账号至app，如果是添加功能管理员，直接跳过去添加
            function (res,callback) {
                if(!res) {//已经有该管理员
                    console.log('添加管理员时，判断产品管理员失败');
                    callback('服务器异常');
                    return;
                }
                if(res == '跳过'){
                    callback(null,'成功');
                    return;
                }
                connection.query('update apps set adm_account = ? where sid = ?',[data.account,data.app_sid],function (err,result) {
                    if(err){
                        callback(err);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,'成功');
                        return;
                    }
                    callback('操作失败');
                });

            },

            //增加管理员  添加该管理员账号至app，如果是添加功能管理员，直接去添加
            function (res,callback) {
                if(!res) {//已经有该管理员
                    console.log('添加管理员时，插入apps表失败');
                    callback('服务器异常');
                    return;
                }

                var admin = {
                    account: data.account,
                    password: data.password,
                    name: data.name,
                    role: data.role,
                    app_sid: data.app_sid
                };

                connection.query('insert into admin set ?',[admin],function (err,result) {
                    if(err){
                        callback(err);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,admin);
                        return;
                    }
                    callback('操作失败');
                });

            }

        ],function (err,adminInfo) {
            if(err){
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            }else {
                connection.commit(function (e) {
                    if(e){
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, adminInfo);
                    }
                });
            }
        });

    });
}

adminManagementDao.updateAdmin = function(data, cb) {
    if(!data) {
        cb(new Error(500));
        return;
    }

    DBFactory.poolQuery('update admin set ? where uid = ?', [data.adminInfo,data.uid],
        function () {
            cb('no collection');
        },
        function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            var res = result.affectedRows > 0 ? '操作成功' : null;
            cb(null,res);
        }
    );

}

//修改管理员状态
adminManagementDao.updateAdminStatus = function (data,cb) {

    if(!data) {
        cb(new Error(500));
        return;
    }
    //修改产品管理员特殊处理
    if(data.isAppAdm == true){
        adminManagementDao.updateAppAdmStatus(data,cb);
    }else {
        //修改普通管理员直接改
        DBFactory.poolQuery('update admin set status = ? where uid = ?', [data.status, data.uid],
            function () {
                cb('no collection');
            },
            function (err, result) {
                if (err) {
                    console.log(err);
                    cb(err);
                    return;
                }
                var res = result.affectedRows > 0 ? '操作成功' : null;
                cb(null, res);
            }
        );
    }
}


//修改产品管理员状态特殊处理
adminManagementDao.updateAppAdmStatus = function (data,cb) {

    DBFactory.getConnection(function(error, connection) {
        if(error) {
            cb(error);
            return;
        }

        async.waterfall([

            function (callback) {
                connection.beginTransaction(function(err) {
                    callback(err);
                });
            },

            //先修改管理员资料
            function (callback) {
                connection.query('update admin set status = ? where uid = ?',[data.status,data.uid],function (err,result) {
                    if(err){
                        console.log('修改管理员状态时，修改admin表失败:' + err);
                        callback(err);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,'成功');
                        return;
                    }
                    callback('操作失败');
                });
            },


            //判断status是改1还是改0： 0改1：判断该产品是否有管理员，有则改失败； 1改0：将产品的管理员account清空
            function (res,callback) {
                if(!res) {
                    console.log('修改管理员状态时，修改admin表失败');
                    callback('服务器异常');
                    return;
                }

                //先查该产品的产品管理员账号
                connection.query("select adm_account from apps where sid = ?",[data.app_sid],function (err,result) {
                    if(err){
                        console.log('添加管理员时，查找apps表失败:' + err);
                        callback(err);
                        return;
                    }
                    var appInfo = (result && result.length > 0) ? result[0] : undefined;
                    if(appInfo){
                        callback(null,appInfo.adm_account);
                    }else {
                        callback(null,null);
                    }
                });
            },

            //0改1：account有 不启用；account无，添加至app；  1改0：account有且相同 ，从app删除； account有不同、account无，不管；
            function (adm_account,callback) {

                if(data.status == 1){

                    if(adm_account){
                        callback('该产品已有产品管理员，启用失败'); //下一个去判断无的情况
                        return;
                    }
                    //直接用data.account给app赋值

                }else if(data.status == 0){

                    if(adm_account != data.account){

                        callback(null,'操作成功');
                        return;


                    }

                    //有account且相等，从apps中删除
                    data.account = null;

                }

                //能到这说明要操作apps表
                connection.query('update apps set adm_account = ? where sid = ?',[data.account,data.app_sid],function (err,result) {
                    if(err){
                        callback(err);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,'操作成功');
                        return;
                    }
                    callback('操作失败');
                });

            }


        ],function (err,adminInfo) {
            if(err){
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            }else {
                connection.commit(function (e) {
                    if(e){
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, adminInfo);
                    }
                });
            }
        });

    });
}



adminManagementDao.findAdmin = function(uid, cb) {//查管理员信息
    if(!uid) {
        cb(new Error(500));
        return;
    }
    DBFactory.poolQuery('select * from admin where uid = ? limit 1', [uid],
        function () {
           cb('no connection');
        },
        function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            var admin = (result && result.length > 0) ? result[0] : undefined;
            cb(null,admin);
        }
    );
}



//查询管理员列表，按名称、手机尾号、产品搜索
adminManagementDao.findAdminList = function(data, cb) {
    if(!data) {
        cb(new Error(500));
        return;
    }
    DBFactory.getConnection(function(error, connection) {
        if(error) {
            cb(error);
            return;
        }

        var sqlInfo = {};
        if(data.app_sid){
            sqlInfo.sql = "select uid,name,account,email,role,app_sid,status from admin where app_sid like '%" + data.app_sid + "%' ";
            sqlInfo.sqlCount = "select count(*) as total from admin where app_sid like '%" + data.app_sid + "%' ";
        }else {
            sqlInfo.sql = "select uid,name,account,email,role,app_sid,status from admin ";
            sqlInfo.sqlCount = "select count(*) as total from admin ";
        }
        if(data.name && data.phoneTail){
            sqlInfo.sql += data.app_sid ? "and name like '%" + data.name + "%' and substring(account,-4) = ?" : "where name like '%" + data.name + "%' and substring(account,-4) = ?";
            sqlInfo.sqlCount += data.app_sid ? "and name like '%" + data.name + "%' and substring(account,-4) = ?" : "where name like '%" + data.name + "%' and substring(account,-4) = ?";
            sqlInfo.valueArr = [data.phoneTail];
        }else if(data.name){
            sqlInfo.sql += data.app_sid ? "and name like '%" + data.name + "%' " : "where name like '%" + data.name + "%' ";
            sqlInfo.sqlCount += data.app_sid ? "and name like '%" + data.name + "%' " : "where name like '%" + data.name + "%' ";
            sqlInfo.valueArr = [];
        }else if(data.phoneTail){
            sqlInfo.sql += data.app_sid ? 'and substring(account,-4) = ?' : 'where substring(account,-4) = ?';
            sqlInfo.sqlCount += data.app_sid ? 'and substring(account,-4) = ?' : 'where substring(account,-4) = ?';
            sqlInfo.valueArr = [data.phoneTail];
        }
        if(data.uid){
            sqlInfo.sql = 'select a.uid,a.name,a.account,a.email,a.role,a.app_sid,a.status,b.name as app_name from admin a left join apps b on a.app_sid = b.sid where a.uid = ?';
            sqlInfo.sqlCount = 'select count(*) as total from admin a left join apps b on a.app_sid = b.sid where a.uid = ?';
            sqlInfo.valueArr = [data.uid];
        }

        connection.query(sqlInfo.sql, sqlInfo.valueArr, function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                connection.release();
                return;
            }

            var adminInfo = {};
            if(data.uid) {//多加一个转换
                result.forEach(function (o) {
                    var roleArr = o.role.split(',');
                    if (o.role.indexOf('admin') >= 0) {
                        o.adminName = '系统管理员';
                    } else if (o.role.indexOf('adm_' + o.app_sid) >= 0) {
                        o.adminName = '产品管理员';
                    } else {
                        o.adminName = '功能管理员';
                    }

                    var roles = [];
                    roleArr.forEach(function (role) {
                        roles.push(role.substr(0,role.indexOf('_' + o.app_sid)));
                    });

                    o.role = roles;

                });

            }
            adminInfo.admins = result;

            connection.query(sqlInfo.sqlCount, sqlInfo.valueArr, function (err, result) {
                if (err) {
                    console.log(err);
                    cb(err);
                    connection.release();
                    return;
                }
                adminInfo.total = (result && result[0]) ? result[0].total : 0;
                cb(null,adminInfo);
                connection.release();
            });
        });

    });

}
